from flask import Blueprint, jsonify
from sqlalchemy import func, extract
from ..models import Employee, Department, Salary
from .. import db
from datetime import datetime, timedelta

bp = Blueprint('dashboard', __name__, url_prefix='/api/dashboard')

@bp.route('/stats/', methods=['GET'])
def get_dashboard_stats():
    total_employees = db.session.query(Employee).count()
    department_count = db.session.query(Department).count()

    current_year = datetime.now().year
    current_month = datetime.now().month

    monthly_salary_total = db.session.query(func.sum(Salary.total_salary)).filter(
        Salary.year == current_year,
        Salary.month == current_month,
        Salary.status == '已发放'
    ).scalar()
    monthly_salary_total = float(monthly_salary_total) if monthly_salary_total else 0.0

    pending_salary_count = db.session.query(Salary).filter_by(status='未发放').count()

    return jsonify({
        'total_employees': total_employees,
        'department_count': department_count,
        'monthly_salary_total': monthly_salary_total,
        'pending_salary_count': pending_salary_count
    })

@bp.route('/department-distribution/', methods=['GET'])
def get_department_distribution():
    department_employees = db.session.query(
        Department.name,
        func.count(Employee.id)
    ).outerjoin(Employee).group_by(Department.name).all()

    data = [{'department_name': name, 'count': count} for name, count in department_employees]
    return jsonify(data)

@bp.route('/salary-trend/', methods=['GET'])
def get_salary_trend():
    today = datetime.now()
    salary_trends = []

    for i in range(6):
        target_date = today - timedelta(days=30 * i) # Approximate previous months
        year = target_date.year
        month = target_date.month

        total_salary_month = db.session.query(func.sum(Salary.total_salary)).filter(
            Salary.year == year,
            Salary.month == month,
            Salary.status == '已发放'
        ).scalar()
        total_salary_month = float(total_salary_month) if total_salary_month else 0.0

        salary_trends.append({
            'month': target_date.strftime('%Y-%m'),
            'total_salary': total_salary_month
        })
    
    # Sort in ascending order by month for chart display
    salary_trends.sort(key=lambda x: x['month'])
    
    return jsonify(salary_trends)

@bp.route('/recent-salaries/', methods=['GET'])
def get_recent_salaries():
    recent_salaries = db.session.query(Salary).join(Employee).order_by(Salary.payment_date.desc()).limit(5).all()

    data = [{
        'id': s.id,
        'employee_name': s.employee.name,
        'department_name': s.employee.department.name if s.employee.department else None,
        'year': s.year,
        'month': s.month,
        'total_salary': float(s.total_salary),
        'status': s.status,
        'payment_date': s.payment_date.strftime('%Y-%m-%d') if s.payment_date else None
    } for s in recent_salaries]

    return jsonify(data) 